'use strict';

const Controller = require('egg').Controller;

const path=require("path")
const fs=require("fs")

const {semdMail}=require("../utils/sendMail")

class HomeController extends Controller {
  async getCode() {
    const { ctx } = this;
    const {code}=ctx.request.query
    const result=await ctx.service.user.get_access_token(code)
    if(result.status==200){
      ctx.body={
        code:"1001",
        msg:"获取access_token成功",
        access_token:result.data.access_token,
        isAbandon:true
      }
    }else{
      ctx.body={
        code:"1002",
        msg:"获取access_token失败",
        isAbandon:true
      }
    }
  }
  async getUserInfo(){
    const {ctx}=this
    const {access_token}=ctx.request.query
    const result=await ctx.service.user.get_user_info(access_token)
    if(result.status==200){
      ctx.body={
        code:"1001",
        msg:"获取获取用户信息成功",
        data:result.data
      }
    }else{
      ctx.body={
        code:"1002",
        msg:"获取获取用户信息失败"
      }
    }
  }

  async uploadController(){
    const {ctx}=this
    const file=ctx.request.files[0]
    const {filename,filepath}=file
    const imgurl=await ctx.service.user.saveAvatar(filename,filepath)
    if(imgurl){
      const result=await ctx.service.user.upload({
        id:ctx.request.query.id,
        imgurl
      })
      if(result.affectedRows){
        ctx.body={
          code:"1001",
          msg:"上传成功",
          imgurl
        }
      }else{
        ctx.body={
          code:"1002",
          msg:"上传失败"
        }
      }
    }else{
      ctx.body={
        code:"1002",
        msg:"获取不到图片信息"
      }
    }
  }

  async ossupload(){
    const {ctx}=this
    const file=ctx.request.files[0]
    const name = '1907c/'+new Date()*1 + path.basename(file.filename);
    let result;
    try {
      result = await ctx.oss.put(name, file.filepath)
    } finally {
      await fs.unlinkSync(file.filepath);
    }
    if (result) {
      if(result.res.status===200){
        const res=await ctx.service.user.upload({
          id:ctx.request.query.id,
          imgurl:result.url
        })
        if(res.affectedRows){
          ctx.body={
            code:"1001",
            msg:"oss上传成功",
            imgurl:result.url
          }
        }else{
          ctx.body={
            code:"1002",
            msg:"oss上传失败"
          }
        }
      }else{
        ctx.body={
          code:"1002",
          msg:"oss上传失败"
        }
      }
    } else {
      ctx.body = 'please select a file to upload';
    }
  }

  async getPwd(){
    const {ctx}=this
    const {id,email}=ctx.request.body
    const result=await semdMail(email,"你好啊","8520")
    if(result.code==200){
      ctx.body={
        code:"1001",
        msg:"发送邮箱成功"
      }
    }else{
      ctx.body={
        code:"1002",
        msg:"发送邮箱失败"
      }
    }
  }
}

module.exports = HomeController;
